<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :title="getTitle"
    @ok="handleSubmit"
    :width="1200"
    style="top: 20px"
  >
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { BasicForm, useForm } from '@/components/Form/index';
  import { formSchema } from './article.data';
  import { createArticle, updateArticle, getArticleInfo } from '@/api/article/article';
  import type { ArticleAddReq, ArticleEditReq } from '@/api/article/model/articleModel';
  import { useMessage } from '@/hooks/web/useMessage';

  const { createMessage } = useMessage();
  const emit = defineEmits(['success', 'register']);
  const isUpdate = ref(true);
  const rowId = ref<number>(0);

  const getTitle = computed(() => (!unref(isUpdate) ? '新增文章' : '编辑文章'));

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 100,
    schemas: formSchema,
    showActionButtonGroup: false,
  });

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    resetFields();
    setModalProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;

    if (unref(isUpdate)) {
      rowId.value = data.record.id;
      console.log(rowId.value);

      try {
        const articleInfo = await getArticleInfo(Number(rowId.value));
        if (articleInfo.cover) {
          articleInfo.cover = [
            {
              url: articleInfo.cover,
              status: 'done',
              name: articleInfo.cover.split('/').pop(),
            },
          ];
        }
        if (articleInfo.tags && articleInfo.tags.length > 0) {
          articleInfo.tag_ids = articleInfo.tags.map((tag) => tag.id);
        }
        setFieldsValue({
          ...articleInfo,
        });
      } catch (error) {
        createMessage.error('获取文章详情失败');
        closeModal();
      }
    }
  });

  async function handleSubmit() {
    try {
      const values = await validate();
      setModalProps({ confirmLoading: true });

      const formData = {
        title: values.title,
        keywords: values.keywords,
        cover: Array.isArray(values.cover) ? values.cover[0]?.url || values.cover[0] : values.cover,
        tag_ids: values.tag_ids || [],
        desc: values.desc,
        content: values.content,
        status: values.status,
      };

      if (unref(isUpdate)) {
        await updateArticle({
          ...formData,
          id: rowId.value,
        } as ArticleEditReq);
      } else {
        await createArticle(formData as ArticleAddReq);
      }

      closeModal();
      emit('success');
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
